package com.wenshi.web.netty;

import com.wenshi.web.netty.handler.MqttClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@Data
public class MqttClient implements Runnable{
    private  String host;
    private  int port;

    private Channel channel;

    private ChannelFuture channelFuture;

    private EventLoopGroup group;

    private Bootstrap bootstrap;

    @SneakyThrows
    @Override
    public void run() {
        group = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast( new MqttDecoder());
                            ch.pipeline().addLast(MqttEncoder.INSTANCE);
                            ch.pipeline().addLast(new MqttClientHandler());
                        }
                    });
            log.info("mqtt客户端已启动。。。。。。。");

            ChannelFuture f = bootstrap.connect(host, port).sync();
            if (f.isSuccess()) {
                log.info("连接mqtt服务器成功: " + host + ":" + port);
            }
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
